/**
 * Reading plain file
 * File format: the first line is number which means the number of object needing to parsing
 * If the fisrt line is not number, reading will be exited.
 */
package data.converter.parser;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class ReadPlainFile{

	private File filePath;
	private int maxLimit = 20;
	private int lineNum = 0;
	
	private BufferedReader reader;
	private List<String> fileContent = new ArrayList<String>();
	
	private static final Logger logger = Logger.getLogger(ReadPlainFile.class.getName());
	
	public ReadPlainFile(File filePath) {
		this.filePath = filePath;
	}
	
	public ReadPlainFile(File filePath, int maxLimit) {
		this.filePath = filePath;
		this.maxLimit = maxLimit;
	}
	/**
	 * 
	 * @return fileContent
	 * @throws IOException
	 * If the first line is not number, method will return empty list
	 */
	public synchronized List<String> readFileToList() throws IOException {
		fileContent.clear();
		boolean existing = checkFile();
		if (!existing) {
			return fileContent;
		}
		logger.log(Level.INFO, "file path: " + filePath.getAbsolutePath());
		reader = new BufferedReader(new FileReader(filePath));
		String counterLine = reader.readLine();
		if(!isNumber(counterLine)) {
			return fileContent;
		}
		lineNum = Integer.parseInt(counterLine);
		for(int i=0; i < lineNum; i++) {
			fileContent.add(reader.readLine());
		}
		return fileContent;
	}
	
	/**
	 * 
	 * @return existing
	 * Check if file exists or can be read
	 */
	public boolean checkFile() {
		boolean existing = true;
		if (filePath == null || !filePath.exists()
				|| !filePath.canRead()) {
			existing = false;
		} 
		
		return existing;
	}
	
	public boolean isNumber(String counterLine) {
		String regex = "[0-9]+";
		Pattern pattern = Pattern.compile(regex);
		Matcher matcher = pattern.matcher(counterLine);
		return matcher.matches();
	}


	public int getMaxLimit() {
		return maxLimit;
	}

	public int getLineNum() {
		return lineNum;
	}	
}
